/**
 * 
 */
package com.tomica.mailsigner.signpdf;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.Wsdl2Code.WebServices.SignService.SignService;
import com.Wsdl2Code.WebServices.SignService.VectorByte;
import com.entersafe.safeca.Constant;
import com.tomica.mailsigner.common.MailSignerEvents;
import com.tomica.mailsigner.token.Token;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

/**
 * Model class of Sign PDF Activity
 * @author TOMICALAB
 *
 */
public class SignPDFModel {

	public Context context; 
	private Token token;
	private SignService service;
	private Handler handler;
	
	

	public SignPDFModel(Context ctx, Handler hdl){
		context = ctx;
		handler = hdl;
		token = new Token(ctx, null);
		MailSignerEvents mailHandleEvents = new MailSignerEvents(handler);
		service = new SignService(mailHandleEvents);
	}

	public void signPdf(byte[] pdfBase64, String pin){
		// TODO : signing here :)
		Log.v("SignPDF", "Starting ^^");
		
		uploadPdfFile(pdfBase64, pin);
		
		return;
	}

	public void signObjectString(String data, String pin){
		Log.v("SignPDF", "Sign object ^^");
		byte[] byteData = Base64.decode(data, Base64.DEFAULT);
		String signData = token.signDataBase64(byteData, pin);
		
		// TODO : handle when sign error
		Message msg = new Message();
        msg.what = Constant.PDF_SIGNED_PKCS_OK;
        msg.obj  = signData;
        handler.sendMessage(msg);
	}

	public void getSignedPdfFile(String randomString, String signatureBase64){
		Log.v("SignPDF", "Get Signed PDF file");
		try {
			service.GetSignedPdfFileAsync(randomString, signatureBase64);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void uploadPdfFile(byte[] fileData, String pin){
		Log.v("SignPDF", "Upload PDF file");
		Log.v("SignPDF", "PDF ByteArray size: "+fileData.length);
		String certBase64 = token.getCertBase64(pin);
		
		try {
			VectorByte vector  = new VectorByte(fileData);
			service.UploadPdfFileAsync(vector, certBase64);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] getBytes(InputStream inputStream) throws IOException {
		
		ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
		int bufferSize = 1024;
		byte[] buffer = new byte[bufferSize];

		int len = 0;
		while ((len = inputStream.read(buffer)) != -1) {
			byteBuffer.write(buffer, 0, len);
		}
		return byteBuffer.toByteArray();
	}
}
